<template>
  <div class="gzzhcx-container">
    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="search-section">
        <el-date-picker
          v-model="selectedWeek"
          type="week"
          format="yyyy 第 WW 周"
          value-format="yyyy-MM-dd"
          placeholder="请选择周"
          class="date-picker-custom week-picker-enhanced"
          :editable="false"
          :clearable="true"
          :picker-options="weekPickerOptions"
          @change="handleWeekChange">
        </el-date-picker>
        <el-button type="primary" @click="handleQuery">查询</el-button>
      </div>
    </div>

    <!-- 操作按钮行 -->
    <!-- <div class="action-bar">
      <el-button type="success" @click="handleExport">导出数据</el-button>
    </div> -->

    <!-- 表格容器 -->
    <div class="table-container">
      <el-table
        :data="queryData"
        border
        stripe
        style="width: 100%"
        height="500"
        class="custom-table">
        <el-table-column
          prop="displayWeek"
          label="时间（周）"
          align="center"
          min-width="200">
        </el-table-column>
        <el-table-column
          prop="num"
          label="上报数量"
          align="center"
          width="150">
          <template slot-scope="scope">
            <span class="count-text">{{ scope.row.num }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="120">
          <template slot-scope="scope">
            <el-button
              type="text"
              class="detail-btn"
              @click="viewDetail(scope.row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>

    </div>
    <!-- 详情对话框 -->
    <el-dialog
      title="查看详情"
      :visible.sync="detailDialogVisible"
      width="90%"
      top="5vh"
      @close="handleDetailClose">
      <!-- Tab切换 -->
      <el-tabs v-model="activeDetailTab" class="detail-tabs" @tab-click="handleDetailTabClick">
        <!-- 表1.配变重过载、低电压 Tab -->
        <el-tab-pane label="预测情况分析" name="table1">
          <!-- 导出按钮 -->
          <div class="detail-action-bar">
            <el-button type="success" @click="handleDetailExport('表1')">导出数据</el-button>
          </div>

          <!-- 表格内容区域 -->
          <div class="detail-table-container">
            <el-table
              :data="table1Data"
              border
              stripe
              style="width: 100%"
              height="300"
              class="detail-table">
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="unit" label="单位" width="120" fixed="left"></el-table-column>
              <el-table-column prop="userName" label="填报人" width="120" fixed="left"></el-table-column>
              <el-table-column prop="phone" label="联系电话" width="120" fixed="left"></el-table-column>
              <!-- 配变（单位：台）列组 -->
              <el-table-column label="配变（单位：台）" align="center">
                <el-table-column prop="totalTransformer" label="总数" width="100" align="center"></el-table-column>
                <el-table-column prop="publicTransformer" label="公变" width="100" align="center"></el-table-column>
                <el-table-column prop="privateTransformer" label="专变" width="100" align="center"></el-table-column>
              </el-table-column>

              <!-- 负载（单位：台）列组 -->
              <el-table-column label="负载（单位：台）" align="center">
                <el-table-column prop="overloadLoad" label="过载" width="100" align="center"></el-table-column>
                <el-table-column prop="heavyLoad" label="重载" width="100" align="center"></el-table-column>
              </el-table-column>

              <!-- 电压（单位：台）列组 -->
              <el-table-column label="电压（单位：台）" align="center">
                <el-table-column prop="severeLowVoltage" label="严重低电压" width="140" align="center"></el-table-column>
                <el-table-column prop="generalLowVoltage" label="一般低电压" min-width="140" align="center"></el-table-column>
              </el-table-column>
            </el-table>
          </div>

          <!-- 分析内容显示区域 -->
          <div class="analysis-content" v-if="analysisContent && !isEditingAnalysis">
            <div class="analysis-header">
              <h4>分析内容：</h4>
              <el-button type="primary" size="mini" @click="editAnalysisContent">编辑</el-button>
            </div>
            <p v-for="(line, index) in analysisContent.split('\n')" :key="index">{{ line }}</p>
          </div>
          <!-- 分析内容编辑区域 -->
          <div class="analysis-content-edit" v-if="isEditingAnalysis">
            <div class="analysis-header">
              <h4>分析内容：</h4>
              <div>
                <el-button type="success" size="mini" @click="saveAnalysisContent">保存</el-button>
                <el-button type="info" size="mini" @click="cancelEditAnalysis">取消</el-button>
              </div>
            </div>
            <el-input
              type="textarea"
              :rows="6"
              v-model="editableAnalysisContent"
              placeholder="请输入分析内容"
              class="analysis-textarea">
            </el-input>
          </div>
        </el-tab-pane>

        <!-- 表2 Tab -->
        <el-tab-pane label="过载配变明细" name="table2">
          <!-- 导出按钮 -->
          <div class="detail-action-bar">
            <el-button type="success" @click="handleDetailExport('表2')" :loading="gzpbtbLoading">导出数据</el-button>
          </div>

          <!-- 表格内容区域 -->
          <div class="detail-table-container">
            <el-table
              :data="gzpbtbData"
              border
              stripe
              style="width: 100%"
              height="300"
              class="detail-table"
              v-loading="gzpbtbLoading">
              <el-table-column type="index" label="序号" width="60"></el-table-column>
              <el-table-column prop="userName" label="填报人" width="100"></el-table-column>
              <el-table-column prop="contactPhone" label="联系电话" width="120"></el-table-column>
              <el-table-column prop="subsidiaryCompany" label="分子公司" width="150"></el-table-column>
              <el-table-column prop="cityBureau" label="地市局" width="120"></el-table-column>
              <el-table-column prop="countyBureau" label="区县局" width="120"></el-table-column>
              <el-table-column prop="substationName" label="变电站名称" width="120"></el-table-column>
              <el-table-column prop="transformerName" label="变压器名称" width="120"></el-table-column>
              <el-table-column prop="transformerGisid" label="变压器GISID" width="120"></el-table-column>
              <el-table-column prop="publicPrivateAttribute" label="公专变属性" width="110"></el-table-column>
              <el-table-column prop="regionalFeatures" label="地区特征" width="100"></el-table-column>
              <el-table-column prop="transformerCapacity" label="变压器容量(kVA)" width="140"></el-table-column>
              <el-table-column prop="phaseNumber" label="相数" width="80"></el-table-column>
              <el-table-column prop="lineName" label="线路名称" width="120"></el-table-column>
              <el-table-column prop="overloadCause" label="引起重过载原因" width="150"></el-table-column>
              <el-table-column prop="preventionMeasures" label="防控措施" width="150"></el-table-column>
              <el-table-column prop="lastMonthOverload" label="上月是否发生月过载" width="160"></el-table-column>
              <el-table-column prop="overloadDays" label="过载天数" width="100"></el-table-column>
              <el-table-column prop="remark" label="备注" min-width="150"></el-table-column>
            </el-table>
          </div>

          <!-- 分析内容显示区域 -->
          <div class="analysis-content" v-if="analysisContent && !isEditingAnalysis">
            <div class="analysis-header">
              <h4>分析内容：</h4>
              <el-button type="primary" size="mini" @click="editAnalysisContent">编辑</el-button>
            </div>
            <p v-for="(line, index) in analysisContent.split('\n')" :key="index">{{ line }}</p>
          </div>
          <!-- 分析内容编辑区域 -->
          <div class="analysis-content-edit" v-if="isEditingAnalysis">
            <div class="analysis-header">
              <h4>分析内容：</h4>
              <div>
                <el-button type="success" size="mini" @click="saveAnalysisContent">保存</el-button>
                <el-button type="info" size="mini" @click="cancelEditAnalysis">取消</el-button>
              </div>
            </div>
            <el-input
              type="textarea"
              :rows="6"
              v-model="editableAnalysisContent"
              placeholder="请输入分析内容"
              class="analysis-textarea">
            </el-input>
          </div>
        </el-tab-pane>

        <!-- 表3 Tab -->
        <el-tab-pane label="低电压台区预测明细" name="table3">
          <!-- 导出按钮 -->
          <div class="detail-action-bar">
            <el-button type="success" @click="handleDetailExport('表3')" :loading="gzdytbLoading">导出数据</el-button>
          </div>

          <!-- 表格内容区域 -->
          <div class="detail-table-container">
            <el-table
              :data="gzdytbData"
              border
              stripe
              style="width: 100%"
              height="300"
              class="detail-table"
              v-loading="gzdytbLoading">
              <el-table-column type="index" label="序号" width="60"></el-table-column>
              <el-table-column prop="userName" label="填报人" width="100"></el-table-column>
              <el-table-column prop="contactPhone" label="联系电话" width="120"></el-table-column>
              <el-table-column prop="subsidiaryCompany" label="分子公司" width="150"></el-table-column>
              <el-table-column prop="cityBureau" label="地市局" width="120"></el-table-column>
              <el-table-column prop="countyBureau" label="区县局" width="120"></el-table-column>
              <el-table-column prop="transformerName" label="变压器名称" width="120"></el-table-column>
              <el-table-column prop="gisid" label="GISID" width="120"></el-table-column>
              <el-table-column prop="transformerCapacity" label="变压器容量(kVA)" width="140"></el-table-column>
              <el-table-column prop="transformerNameShort" label="变名称" width="100"></el-table-column>
              <el-table-column prop="transformerType" label="变压器类型" width="110"></el-table-column>
              <el-table-column prop="lineName" label="线路名称" width="120"></el-table-column>
              <el-table-column prop="regionalFeatures" label="地区特征" width="100"></el-table-column>
              <el-table-column prop="lowVoltagePrediction" label="预测是否为严重低电压" width="170"></el-table-column>
              <el-table-column prop="specialOperationLowVoltage" label="是否为特殊运行方式引起短期低电压" width="210"></el-table-column>
              <el-table-column prop="lowVoltageCause" label="引起低电压的原因" width="150"></el-table-column>
              <el-table-column prop="preventionMeasures" label="防控措施" width="150"></el-table-column>
              <el-table-column prop="remark" label="备注" min-width="150"></el-table-column>
            </el-table>
          </div>

          <!-- 分析内容显示区域 -->
          <div class="analysis-content" v-if="analysisContent && !isEditingAnalysis">
            <div class="analysis-header">
              <h4>分析内容：</h4>
              <el-button type="primary" size="mini" @click="editAnalysisContent">编辑</el-button>
            </div>
            <p v-for="(line, index) in analysisContent.split('\n')" :key="index">{{ line }}</p>
          </div>
          <!-- 分析内容编辑区域 -->
          <div class="analysis-content-edit" v-if="isEditingAnalysis">
            <div class="analysis-header">
              <h4>分析内容：</h4>
              <div>
                <el-button type="success" size="mini" @click="saveAnalysisContent">保存</el-button>
                <el-button type="info" size="mini" @click="cancelEditAnalysis">取消</el-button>
              </div>
            </div>
            <el-input
              type="textarea"
              :rows="6"
              v-model="editableAnalysisContent"
              placeholder="请输入分析内容"
              class="analysis-textarea">
            </el-input>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'GzzhcxIndex',
  data() {
    return {
      // 周选择器相关
      selectedWeek: '',
      weekPickerOptions: {
        firstDayOfWeek: 1, // 周一作为一周的第一天
        disabledDate(time) {
          return false // 不禁用任何日期
        },
        shortcuts: [
          {
            text: '本周',
            onClick(picker) {
              const now = new Date()
              const day = now.getDay()
              const diff = now.getDate() - day + (day === 0 ? -6 : 1) // 计算周一的日期
              const monday = new Date(now.setDate(diff))
              picker.$emit('pick', monday)
            }
          },
          {
            text: '上周',
            onClick(picker) {
              const now = new Date()
              const day = now.getDay()
              const diff = now.getDate() - day + (day === 0 ? -6 : 1) - 7 // 上周一
              const lastMonday = new Date(now.setDate(diff))
              picker.$emit('pick', lastMonday)
            }
          },
          {
            text: '下周',
            onClick(picker) {
              const now = new Date()
              const day = now.getDay()
              const diff = now.getDate() - day + (day === 0 ? -6 : 1) + 7 // 下周一
              const nextMonday = new Date(now.setDate(diff))
              picker.$emit('pick', nextMonday)
            }
          }
        ]
      },
      // 查询结果数据
      queryData: [],
      // 详情对话框相关
      detailDialogVisible: false,
      activeDetailTab: 'table1',
      currentDetailItem: null,
      // 修改用于存储分析内容的变量
      analysisContent: '',
      // 添加用于存储编辑状态的变量
      isEditingAnalysis: false,
      editableAnalysisContent: '',
      // gzpbtb数据加载状态
      gzpbtbLoading: false,
      gzpbtbData: [],
      // gzdytb数据加载状态
      gzdytbLoading: false,
      gzdytbData: [],
      // 详情表格数据（初始为空，通过接口加载）
      table1Data: [],
      table2Data: [
        {
          itemName: '线路损耗',
          value: '12.5',
          unit: 'kW',
          status: '正常',
          remark: '在允许范围内'
        },
        {
          itemName: '变压器损耗',
          value: '8.3',
          unit: 'kW',
          status: '异常',
          remark: '超出标准值'
        }
      ],
      table3Data: [
        {
          deviceName: '开关柜1号',
          location: 'A区1楼',
          type: '低压开关柜',
          parameter: '400A',
          description: '主电源开关柜'
        },
        {
          deviceName: '电缆分接箱2号',
          location: 'B区2楼',
          type: '电缆分接箱',
          parameter: '250A',
          description: '二级配电设备'
        }
      ]
    }
  },
  mounted() {
    // 初始化时加载数据
    this.loadData()
  },
  methods: {
    // 加载数据
    loadData() {
      // 构建查询参数
      const params = {}

      // 如果有选择周期，转换为数字格式后添加到查询参数
      if (this.selectedWeek) {
        params.reportWeek = this.convertDateToWeekFormat(this.selectedWeek)
      }

      // 调用综合查询接口
      let proxy = {
        url: '/pbcgzGzyctb/query/zonghe',
        data: params
      }

      this.$oPost({ proxy }, (d) => {
        if (d.code === 1000) {
          // 确保 data 存在且格式正确
          if (d.data && d.data.list && Array.isArray(d.data.list)) {
            // 映射返回的数据字段到表格需要的字段
            this.queryData = d.data.list.map(item => ({
              week: item.week,  // 保存原始 week 值
              displayWeek: this.convertWeekFormatToDisplay(item.week),  // 用于显示的格式
              num: item.num
            }))
          } else {
            console.error('综合查询 API 返回数据格式不正确:', d)
            this.$message.error('数据格式异常')
            this.queryData = []
          }
        } else {
          console.error('综合查询 API 请求失败:', d)
          this.$message.error(d.message || '查询失败')
          this.queryData = []
        }
      }, (error) => {
        console.error('综合查询 API 请求出错:', error)
        this.$message.error('网络请求失败')
        this.queryData = []
      })
    },

    // 周选择变化处理
    handleWeekChange(value) {
      this.loadData()
      if (value) {
        this.$message.success(`已选择周期：${this.formatWeekDisplay(value)}`)
      }
    },

    // 查询按钮处理
    handleQuery() {
      this.loadData()
      this.$message.success('查询功能已触发')
    },

    // 导出数据处理
    handleExport() {
      this.$message.success('导出功能已触发')
      // 这里可以添加具体的导出逻辑
      console.log('执行导出操作')
    },

    // 查看详情处理
    viewDetail(item) {
      this.currentDetailItem = item
      this.detailDialogVisible = true
      this.activeDetailTab = 'table1'

      // 加载预测情况分析数据，传递原始的 week 值
      this.loadTable1Data(item.week)

      // 调用接口获取分析内容
      this.loadAnalysisContent(item.week)

      console.log('查看详情:', item)
    },

    // 加载gzpbtb数据
    loadGzpbtbData(originalWeek) {
      this.gzpbtbLoading = true

      // 构建查询参数
      const params = {
        status: '1'  // 固定传1
      }

      // 如果有原始 week 值，添加到查询参数
      if (originalWeek) {
        params.reportWeek = originalWeek
      }

      let proxy = {
        url: 'pbcgzGzpbtb/all',
        data: params
      }

      this.$oPost({ proxy }, (d) => {
        this.gzpbtbLoading = false
        if (d.code === 1000) {
          // 确保 data 存在且格式正确
          if (d.data && d.data.list && Array.isArray(d.data.list)) {
            this.gzpbtbData = d.data.list
          } else {
            console.error('gzpbtb API 返回数据格式不正确:', d)
            this.$message.error('数据格式异常')
            this.gzpbtbData = []
          }
        } else {
          console.error('gzpbtb API 请求失败:', d)
          this.$message.error(d.message || '查询失败')
          this.gzpbtbData = []
        }
      }, (error) => {
        this.gzdytbLoading = false
        console.error('gzpbtb API 请求出错:', error)
        this.$message.error('网络请求失败')
        this.gzpbtbData = []
      })
    },

    // 加载gzdytb数据
    loadGzdytbData(originalWeek) {
      this.gzdytbLoading = true

      // 构建查询参数
      const params = {
        status: '1'  // 固定传1
      }

      // 如果有原始 week 值，添加到查询参数
      if (originalWeek) {
        params.reportWeek = originalWeek
      }

      let proxy = {
        url: 'pbcgzGzdytb/all',
        data: params
      }

      this.$oPost({ proxy }, (d) => {
        this.gzdytbLoading = false
        if (d.code === 1000) {
          // 确保 data 存在且格式正确
          if (d.data && d.data.list && Array.isArray(d.data.list)) {
            this.gzdytbData = d.data.list
          } else {
            console.error('gzdytb API 返回数据格式不正确:', d)
            this.$message.error('数据格式异常')
            this.gzdytbData = []
          }
        } else {
          console.error('gzdytb API 请求失败:', d)
          this.$message.error(d.message || '查询失败')
          this.gzdytbData = []
        }
      }, (error) => {
        this.gzdytbLoading = false
        console.error('gzdytb API 请求出错:', error)
        this.$message.error('网络请求失败')
        this.gzdytbData = []
      })
    },

    // 详情Tab切换处理
    handleDetailTabClick(tab, event) {
      console.log('切换到Tab:', tab.name)
      // 当点击预测情况分析Tab时，加载gzyctb数据
      if (tab.name === 'table1' && this.table1Data.length === 0) {
        // 提取原始的 week 值用于传递给详情接口
        const originalWeek = this.extractOriginalWeek(this.currentDetailItem.week)
        this.loadTable1Data(originalWeek)
      }
      // 当点击过载配变明细Tab时，加载gzpbtb数据
      if (tab.name === 'table2' && this.gzpbtbData.length === 0) {
        // 提取原始的 week 值用于传递给详情接口
        const originalWeek = this.extractOriginalWeek(this.currentDetailItem.week)
        this.loadGzpbtbData(originalWeek)
      }
      // 当点击低电压台区预测明细Tab时，加载gzdytb数据
      if (tab.name === 'table3' && this.gzdytbData.length === 0) {
        // 提取原始的 week 值用于传递给详情接口
        const originalWeek = this.extractOriginalWeek(this.currentDetailItem.week)
        this.loadGzdytbData(originalWeek)
      }
    },

    // 详情对话框关闭处理
    handleDetailClose() {
      this.detailDialogVisible = false
      this.currentDetailItem = null
      this.activeDetailTab = 'table1'
      // 清理所有详情数据
      this.table1Data = []
      this.gzpbtbData = []
      this.gzpbtbLoading = false
      this.gzdytbData = []
      this.gzdytbLoading = false
      // 清空分析内容
      this.analysisContent = ''
      // 重置编辑状态
      this.isEditingAnalysis = false
      this.editableAnalysisContent = ''
    },

    // 提取原始的 week 值
    extractOriginalWeek(displayWeek) {
      // 如果已经是原始格式（如 "202533"），直接返回
      if (displayWeek && displayWeek.length === 6 && !displayWeek.includes('.')) {
        return displayWeek
      }

      // 如果是显示格式（如 "2025.8.11-17"），需要重新计算原始值
      // 为了简化，这里我们假设在 loadData 时已经保存了原始值
      // 在实际应用中，您可能需要根据显示的日期重新计算原始 week 值
      return displayWeek
    },

    // 加载分析内容
    loadAnalysisContent(originalWeek) {
      // 构建查询参数
      const params = {}

      // 如果有原始 week 值，添加到查询参数
      if (originalWeek) {
        params.reportWeek = originalWeek
      }

      let proxy = {
        url: 'pbcgzGzyctb/buildContentRule',
        data: params
      }

      this.$oPost({ proxy }, (d) => {
        if (d.code === 1001) {
          // 解析返回的字符串，按表格分类
          this.parseAnalysisContent(d.msg)
        } else {
          console.error('分析内容 API 请求失败:', d)
          this.$message.error(d.message || '获取分析内容失败')
        }
      }, (error) => {
        console.error('分析内容 API 请求出错:', error)
        this.$message.error('网络请求失败')
      })
    },

    // 解析分析内容
    parseAnalysisContent(content) {
      if (!content) return

      // 直接保存完整的分析内容，不做区分
      this.analysisContent = content
    },

    // 加载预测情况分析数据
    loadTable1Data(originalWeek) {
      // 构建查询参数
      const params = {
        status: '1'  // 固定传1
      }

      // 如果有原始 week 值，添加到查询参数
      if (originalWeek) {
        params.reportWeek = originalWeek
      }

      let proxy = {
        url: 'pbcgzGzyctb/all',
        data: params
      }

      this.$oPost({ proxy }, (d) => {
        if (d.code === 1000) {
          // 确保 data 存在且格式正确
          if (d.data && d.data.list && Array.isArray(d.data.list)) {
            this.table1Data = d.data.list
          } else {
            console.error('gzyctb API 返回数据格式不正确:', d)
            this.$message.error('数据格式异常')
            this.table1Data = []
          }
        } else {
          console.error('gzyctb API 请求失败:', d)
          this.$message.error(d.message || '查询失败')
          this.table1Data = []
        }
      }, (error) => {
        console.error('gzyctb API 请求出错:', error)
        this.$message.error('网络请求失败')
        this.table1Data = []
      })
    },

    // 详情导出处理
    handleDetailExport(tableName) {
      // 获取当前选中的周信息
      const originalWeek = this.currentDetailItem ? this.currentDetailItem.week : null;

      // 所有Tab都调用/pbcgzGzdytb/exportExcel接口
      const params = {
        reportWeek: originalWeek,
        status: '1',
        descp: this.analysisContent || '' // 分析内容
      };

      // 根据当前激活的Tab设置加载状态
      if (this.activeDetailTab === 'table2') {
        this.gzpbtbLoading = true;
      } else if (this.activeDetailTab === 'table3') {
        this.gzdytbLoading = true;
      }

      // 调用导出接口
      let proxy = {
        url: '/pbcgzGzyctb/exportExcel',
        data: params,
        responseType: 'blob' // 重要：设置响应类型为blob以处理文件下载
      };

      this.$oPost({ proxy }, (response) => {
        // 根据当前激活的Tab重置加载状态
        if (this.activeDetailTab === 'table2') {
          this.gzpbtbLoading = false;
        } else if (this.activeDetailTab === 'table3') {
          this.gzdytbLoading = false;
        }

        // 创建下载链接
        const blob = new Blob([response], { type: 'application/vnd.ms-excel' });
        const fileName = `数据导出_${tableName}_${originalWeek || '未知时间'}.xlsx`;

        // 创建并触发下载
        // if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        //   // IE浏览器
        //   window.navigator.msSaveOrOpenBlob(blob, fileName);
        // } else {
          // 其他浏览器
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.download = fileName;
          link.style.display = 'none';
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
        // }

        this.$message.success(`导出${tableName}数据成功！`);
      }, (error) => {
        // 根据当前激活的Tab重置加载状态
        if (this.activeDetailTab === 'table2') {
          this.gzpbtbLoading = false;
        } else if (this.activeDetailTab === 'table3') {
          this.gzdytbLoading = false;
        }
        console.error('导出失败:', error);
        this.$message.error('导出失败：' + (error.message || '网络请求失败'));
      });
    },

    // 日期转换方法
    convertDateToWeekFormat(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      const year = date.getFullYear()
      const weekOfYear = this.getWeekOfYear(date)
      return year + String(weekOfYear).padStart(2, '0')
    },

    convertWeekFormatToDisplay(weekStr) {
      if (!weekStr || weekStr.length !== 6) return weekStr
      const year = parseInt(weekStr.substring(0, 4))
      const week = parseInt(weekStr.substring(4, 6))

      // 使用更准确的ISO 8601周计算方法
      // 创建1月4日的日期（总是属于第一周）
      const jan4 = new Date(year, 0, 4)
      const jan4Day = jan4.getDay()
      // 计算第一周的周一
      const firstMonday = new Date(jan4)
      const daysToMonday = jan4Day === 0 ? -6 : 1 - jan4Day
      firstMonday.setDate(4 + daysToMonday)

      // 计算目标周的周一
      const targetMonday = new Date(firstMonday)
      targetMonday.setDate(firstMonday.getDate() + (week - 1) * 7)

      // 计算该周的周日
      const targetSunday = new Date(targetMonday)
      targetSunday.setDate(targetMonday.getDate() + 6)

      // 格式化显示
      const startYear = targetMonday.getFullYear()
      const startMonth = targetMonday.getMonth() + 1
      const startDay = targetMonday.getDate()
      const endYear = targetSunday.getFullYear()
      const endMonth = targetSunday.getMonth() + 1
      const endDay = targetSunday.getDate()

      // 如果是同一年
      if (startYear === endYear) {
        return `${startYear}.${startMonth}.${startDay}-${endMonth}.${endDay}`
      } else {
        // 跨年的情况
        return `${startYear}.${startMonth}.${startDay}-${endYear}.${endMonth}.${endDay}`
      }
    },

    formatWeekDisplay(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      const year = date.getFullYear()
      const weekOfYear = this.getWeekOfYear(date)
      return `${year}年第${weekOfYear}周`
    },

    getWeekOfYear(date) {
      const firstDay = new Date(date.getFullYear(), 0, 1)
      const pastDaysOfYear = (date - firstDay) / 86400000
      return Math.ceil((pastDaysOfYear + firstDay.getDay() + 1) / 7)
    },

    // 编辑分析内容
    editAnalysisContent() {
      this.isEditingAnalysis = true
      this.editableAnalysisContent = this.analysisContent
    },

    // 保存分析内容
    saveAnalysisContent() {
      this.analysisContent = this.editableAnalysisContent
      this.isEditingAnalysis = false
      this.$message.success('分析内容已保存')
    },

    // 取消编辑分析内容
    cancelEditAnalysis() {
      this.isEditingAnalysis = false
      this.editableAnalysisContent = ''
    },
  }
}
</script>

<style scoped>
.gzzhcx-container {
  background: #f5f5f5;
  min-height: 100vh;
  padding: 0;
}

/* 工具栏样式 */
.toolbar {
  background: #fff;
  padding: 16px 24px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.search-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 日期选择器样式 */
.date-picker-custom {
  width: 250px;
}

.week-picker-enhanced .el-input__inner {
  border-radius: 4px;
  font-size: 14px;
  border: 1px solid #dcdfe6;
}

.week-picker-enhanced .el-input__inner:focus {
  border-color: #409EFF;
  outline: none;
}

.week-picker-enhanced .el-input__inner:hover {
  border-color: #c0c4cc;
}

/* 操作按钮行样式 */
.action-bar {
  background: #fff;
  padding: 12px 24px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  gap: 12px;
  align-items: center;
}

.action-bar .el-button {
  border-radius: 4px;
  font-size: 14px;
  padding: 8px 20px;
  min-width: 80px;
}

/* 表格容器 */
.table-container {
  background: #fff;
  margin: 0;
  padding: 24px;
}

/* Element Table 自定义样式 */
.custom-table {
  border: none;
}

.custom-table .el-table__header-wrapper {
  background-color: #fff;
}

.custom-table .el-table__header th {
  background-color: #fafafa;
  border-bottom: 1px solid #ebeef5;
  border-right: 1px solid #ebeef5;
  color: #606266;
  font-weight: 500;
  padding: 12px 0;
}

.custom-table .el-table__header th:last-child {
  border-right: none;
}

.custom-table .el-table__body-wrapper {
  border: none;
}

.custom-table .el-table__body tr {
  background-color: #fff;
}

.custom-table .el-table__body tr:hover {
  background-color: #f5f7fa;
}

.custom-table .el-table__body td {
  border-bottom: 1px solid #ebeef5;
  border-right: 1px solid #ebeef5;
  padding: 16px 0;
}

.custom-table .el-table__body td:last-child {
  border-right: none;
}

.custom-table .el-table__body tr:last-child td {
  border-bottom: none;
}

/* 表格内容样式 */
.count-text {
  font-size: 16px;
  font-weight: 500;
  color: #409EFF;
}

.detail-btn {
  color: #409EFF;
  font-size: 14px;
  padding: 0;
  text-decoration: none;
}

.detail-btn:hover {
  color: #66b1ff;
  text-decoration: underline;
}

/* 表格样式优化 */
.el-table {
  border-radius: 0;
  border: 1px solid #ebeef5;
}

.el-table th {
  background-color: #fafafa;
  color: #606266;
  font-weight: 500;
  font-size: 14px;
  height: 48px;
}

.el-table td {
  font-size: 14px;
  height: 48px;
}

/* 详情对话框样式 */
.detail-tabs {
  margin-top: 0;
}

.detail-tabs .el-tabs__header {
  margin: 0 0 20px 0;
  background: #fafafa;
  padding: 0 20px;
  border-bottom: 1px solid #e4e7ed;
}

.detail-tabs .el-tabs__nav-wrap {
  padding: 0;
}

.detail-tabs .el-tabs__item {
  height: 48px;
  line-height: 48px;
  font-size: 14px;
  padding: 0 20px;
  background: #fafafa;
  border-right: 1px solid #e4e7ed;
  color: #606266;
}

.detail-tabs .el-tabs__item.is-active {
  background: #fff;
  border-bottom: 2px solid #409EFF;
  color: #409EFF;
  font-weight: 500;
}

.detail-tabs .el-tabs__content {
  padding: 0;
}

.detail-action-bar {
  background: #fff;
  padding: 12px 0;
  margin-bottom: 16px;
  display: flex;
  justify-content: flex-start;
  border-bottom: 1px solid #e4e7ed;
}

.detail-action-bar .el-button {
  margin-right: 12px;
}

.detail-table-container {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.detail-table {
  border: none;
}

.detail-table .el-table__header-wrapper {
  background-color: #fff;
}

.detail-table .el-table__header th {
  background-color: #fafafa;
  border-bottom: 1px solid #ebeef5;
  border-right: 1px solid #ebeef5;
  color: #606266;
  font-weight: 500;
  padding: 12px 0;
}

.detail-table .el-table__header th:last-child {
  border-right: none;
}

.detail-table .el-table__body-wrapper {
  border: none;
}

.detail-table .el-table__body tr {
  background-color: #fff;
}

.detail-table .el-table__body tr:hover {
  background-color: #f5f7fa;
}

.detail-table .el-table__body td {
  border-bottom: 1px solid #ebeef5;
  border-right: 1px solid #ebeef5;
  padding: 12px 0;
}

.detail-table .el-table__body td:last-child {
  border-right: none;
}

.detail-table .el-table__body tr:last-child td {
  border-bottom: none;
}

/* 对话框样式 */
.el-dialog {
  border-radius: 8px;
}

.el-dialog__header {
  background-color: #fafafa;
  border-bottom: 1px solid #e4e7ed;
  padding: 20px 24px;
}

.el-dialog__title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.el-dialog__body {
  padding: 20px 24px;
}

/* 分析内容样式 */
.analysis-content, .analysis-content-edit {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border-left: 4px solid #409EFF;
}

.analysis-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.analysis-header h4 {
  margin: 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.analysis-content p {
  margin: 5px 0;
  color: #606266;
  font-size: 13px;
  line-height: 1.5;
}

.analysis-textarea {
  width: 100%;
}

.analysis-textarea .el-textarea__inner {
  font-size: 13px;
  line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .search-section {
    justify-content: center;
  }

  .action-bar {
    justify-content: center;
    flex-wrap: wrap;
    gap: 8px;
  }

  .action-bar .el-button {
    min-width: 70px;
    padding: 6px 12px;
  }

  .table-container {
    padding: 16px;
  }

  .el-table {
    font-size: 12px;
  }
}

@media (max-width: 576px) {
  .toolbar {
    padding: 12px 16px;
  }

  .action-bar {
    padding: 8px 16px;
  }

  .search-section .el-input {
    width: 200px !important;
  }

  .date-picker-custom {
    width: 200px !important;
  }

  .table-container {
    padding: 12px;
  }

  .detail-tabs .el-tabs__header {
    padding: 0 12px;
  }

  .detail-tabs .el-tabs__item {
    padding: 0 12px;
    font-size: 13px;
  }

  .detail-action-bar {
    padding: 8px 0;
  }

  .el-dialog__body {
    padding: 12px;
  }
}
</style>
